<template>
  <div class="upload-file">
    <el-upload :action="uploadFileUrl"
               :before-upload="handleBeforeUpload"
               :file-list="fileList"
               :limit="limit"
               :on-error="handleUploadError"
               :on-exceed="handleExceed"
               :on-success="handleUploadSuccess"
               :show-file-list="false"
               :headers="headers"
               :drag="isDrag"
               :data="{fileType: oFileType}"
               :hidden="isReadonly"
               class="upload-file-uploader"
               ref="fileUpload"
               multiple>
      <!-- 上传按钮 -->
      <el-button type="primary" v-if="!isDrag"><svg-icon icon-class="invoice" />上传发票</el-button>
      <el-icon v-if="isDrag" class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text" v-if="isDrag">
        将文件拖到此处 <em>点击上传</em>
      </div>
    </el-upload>
    <!-- 上传提示 -->
    <div class="el-upload__tip" v-if="showTip" :hidden="isReadonly">
      请上传
      <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
      <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
      的文件
    </div>
    <!-- 文件列表 -->
    <!--
    <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul" v-if="isShowFileList">
      <li :key="file.uid" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList">
        <span class="el-icon-document"> {{ file.original }} </span>
        <div class="ele-upload-list__item-content-action">
          <el-link :underline="true" @click="handleDownload(file)" type="success">下载</el-link>
          <el-link :underline="true" @click="handlePreview(file)" type="success">预览</el-link>
          <el-link :underline="true" @click="handleDelete(index)" type="danger" v-if="!isReadonly">删除</el-link>
        </div>
      </li>
      -->
      <ul class="files-url" v-if="isShowFileList">
        <li v-for="(item1,index1) in fileList" :key="item1.id">
          <div class="file-text">
            <div>
              <span class="file-name">{{ item1.attachmentName }}</span>
              <span class="file-kb">{{ bytesToSize(item1.attachmentSize) }}</span>
            </div>
            <div>
              <span class="file-time">{{ showIdLabel(userList, item1.attachmentUploader, 'name') }}<span style="color:#333;">上传于</span>{{ item1.attachmentUpload }}</span>
            </div>
          </div>
          <div class="file-btn">
            <el-button type="primary" link @click="handleDownload(item1)">下载</el-button>
            <el-button type="primary" link @click="handlePreview(item1)">预览</el-button>
            <el-button type="danger" link @click="deleteBtn(travelFeeFileList,index,index1)">删除</el-button>
            <el-popover placement="bottom" :width="900" trigger="click">
              <template #reference>
                <el-button type="primary" link>发票详情</el-button>
              </template>
              <div class="report-form-list-content report-form-list-content-be">
                <el-form-item label="发票代码">
                  <el-input v-model="item1.invoiceCode" />
                </el-form-item>
                <el-form-item label="发票号码">
                  <el-input v-model="item1.invoiceNumber" />
                </el-form-item>
                <el-form-item label="开票日期">
                  <el-input v-model="item1.invoiceDate" />
                </el-form-item>
                <el-form-item label="价税合计（元）">
                  <el-input v-model="item1.invoiceTotal" type="number" />
                </el-form-item>
                <el-form-item label="校验码">
                  <el-input v-model="item1.invoiceValid" />
                </el-form-item>
                <el-form-item label="发票名称">
                  <el-input v-model="item1.invoiceBuyerName" />
                </el-form-item>
                <el-form-item label="价税合计(大写)">
                  <el-input v-model="item1.invoiceTotalText" />
                </el-form-item>
                <el-form-item label="价税合计(小写)">
                  <el-input v-model="item1.invoiceTotal" />
                </el-form-item>
                <el-form-item label="销售方名称">
                  <el-input v-model="item1.invoiceSellerName" />
                </el-form-item>
                <el-form-item label="销售方纳税人识别号">
                  <el-input v-model="item1.invoiceSeller" />
                </el-form-item>
                <el-form-item label="销售方开户行及账号">
                  <el-input v-model="item1.invoiceSellerBank" />
                </el-form-item>
                <el-form-item label="销售方地址/电 话">
                  <el-input v-model="item1.invoiceSellerInfo" />
                </el-form-item>
                <el-form-item label="收款人">
                  <el-input v-model="item1.invoicePayee" />
                </el-form-item>
                <el-form-item label="开票人">
                  <el-input v-model="item1.invoicePrinter" />
                </el-form-item>
                <el-form-item label="复核">
                  <el-input v-model="item1.invoiceApprover" />
                </el-form-item>
              </div>
            </el-popover>
          </div>
        </li>
    </ul>
    <!-- </transition-group> -->
  </div>
  <el-dialog v-model="attachmentVisible" title="附件预览" width="70%" top="2vh">
    <attachmentPreview v-model:attachmentId="previewAttachmentId" />
    <div style="text-align:right;">
      <el-button type="danger" @click="closeBtn">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script setup>
import { getToken } from "@/config/cookie";
import {computed, getCurrentInstance, ref, watch} from "vue";
import {doDownload} from "@/config/http"
import {alertErrorMsg, alertWarningMsg, bytesToSize, showIdLabel, svc} from "@/config/common"
import attachmentPreview from '@/views/components/base/attachmentPreview.vue'

const props = defineProps({
  modelValue: [String, Object, Array],
  // 数量限制
  limit: {
    type: Number,
    default: 100,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 5,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ["doc", "docx", "xls", "xlsx", "ppt", "txt", "pdf" , "pptx", "png", "jpg", "jpeg"],
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  },
  // 是否拖拽文件上传
  isDrag: {
    type: Boolean,
    default: false
  },
  // 是否显示文件列表
  isShowFileList: {
    type: Boolean,
    default: true
  },
  isReadonly: {
    type: Boolean,
    default: false,
  },
});

let attachmentVisible = ref(false)
const { proxy } = getCurrentInstance();
const previewAttachmentId = ref(null)
const emit = defineEmits(['uploadedSuccess']);
const number = ref(0);
let uploadList = [];
const uploadFileUrl = ref("/" + svc + "/api/v1/customAttachment/uploadInvoice"); // 上传文件服务器地址
const headers = ref({ Authorization: "Bearer " + getToken() });
const fileList = ref([]);
const showTip = computed(
  () => props.isShowTip && (props.fileType || props.fileSize)
);
const oFileType = ref('')

watch(() => props.modelValue, val => {
  if (val) {
    let temp = 1;
    // 首先将值转为数组
    const list = Array.isArray(val) ? val : props.modelValue.split(',');
    // 然后将数组转为对象数组
    fileList.value = list.map(item => {
      if (typeof item === "string") {
        item = { name: item, url: item };
      }
      item.uid = item.uid || new Date().getTime() + temp++;
      return item;
    });
  } else {
    fileList.value = [];
    return [];
  }
},{ deep: true, immediate: true });

// 上传前校检格式和大小
function handleBeforeUpload(file) {
  // 校检文件类型
  if (props.fileType.length) {
    const fileName = file.name.split('.');
    const fileExt = fileName[fileName.length - 1];
    oFileType.value = fileExt
    const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
    if (!isTypeOk) {
      alertWarningMsg(`文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`);
      return false;
    }
  }
  // 校检文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      alertWarningMsg(`上传文件大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  proxy.$modal.loading("正在上传文件，请稍候...");
  number.value++;
  return true;
}

// 文件预览
function handlePreview(file) {
  console.log('file----------预览',file)
  attachmentVisible.value = true
  setTimeout(() => {
    previewAttachmentId.value = file.id
  },100)
}

function closeBtn() {
  attachmentVisible.value = false
}
// 文件个数超出
function handleExceed() {
  alertWarningMsg(`上传文件数量不能超过 ${props.limit} 个!`);
}

// 上传失败
function handleUploadError(err) {
  proxy.$modal.closeLoading();
  let e = JSON.parse(err.message)
  let msg = e?.message || '上传文件失败'
  alertErrorMsg(msg);
}

// 上传成功回调
function handleUploadSuccess(res, file) {
  // console.log('res-----------',res)
  proxy.$modal.closeLoading();
  if (res.code === '000') {
    uploadList.push(res.data);
    uploadedSuccessfully();

  } else {
    number.value--;
    alertWarningMsg(res.msg);
    proxy.$refs['fileUpload'].handleRemove(file);
    uploadedSuccessfully();
  }
}

function handleDownload(file) {
  doDownload(svc, '/customAttachment/download/' + file.id, {})
}

// 删除文件
function handleDelete(index) {
  fileList.value.splice(index, 1);
  // emit("update:modelValue", listToString(fileList.value));
  emit("update:modelValue", fileList.value);
}

// 上传结束处理
function uploadedSuccessfully() {
  console.log('number',number.value)
  console.log('uploadList',uploadList.value)
  if (number.value > 0 && uploadList.length === number.value) {
    fileList.value = fileList.value.concat(uploadList)
    uploadList = [];
    number.value = 0;
    let oFile = fileList.value.map(item => {
      item.fileType = ''
      return item
    })
    emit("update:modelValue", oFile);
    console.log('oFile---------------',oFile)
    emit('uploadedSuccess', oFile[oFile.length - 1])
    proxy.$modal.closeLoading();
  }
}

// 对象转成指定字符串分隔
function listToString(list, separator) {
  let strs = "";
  separator = separator || ",";
  for (let i in list) {
    if (list[i].url) {
      strs += list[i].url + separator;
    }
  }
  return strs !== '' ? strs.substring(0, strs.length - 1) : '';
}
</script>
<style>
.report-form-list-content {
  display: flex;
    flex-wrap: wrap;
}
</style>
<style scoped lang="scss">
.el-upload__text {
  margin: 0 100px;
}
.el-upload-list {
  margin: 0 !important;
}
.upload-file-uploader {
  display: flex;
  justify-content: left;
}
.upload-file-list .el-upload-list__item {
  border: 0 solid #e4e7ed;
  line-height: 2;
  margin-bottom: 8px;
  position: relative;
}
.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}
.ele-upload-list__item-content-action .el-link {
  margin: 0 10px;
}
.files-url {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
.files-url li {
  list-style-type: none;
  margin: 5px;
  padding: 0;
  border: 1px solid #1ab394;
  background-color: #eaffea;
}
.files-url li {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 5px 10px;
}
.files-url li span {
  padding: 0 5px;
  font-size: 12px;
  font-weight: bold;
}
.file-name {
  color: #202121;
}
.file-kb {
  color: #909399
}
.file-time {
  color: #3e791b;
}

</style>
